package fresita;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Controller {
    private model.Config config;
    /** Creates a new instance of Controller */
    public Controller() {
        config = new model.Config();
        check();
    }
    
    private void check()
    {
        String ingredientDir = config.getValue( "ingredient dir", "ingredients" );
        String recipeDir = config.getValue( "recipe dir", "recipes" );
        
        // si existen no hace nada
        util.Util.createDir(ingredientDir);
        util.Util.createDir(recipeDir);
    }
    
    public model.Recipe getRecipe(String fileName)
    {
        String recipeDir = config.getValue( "recipe dir", "recipes" );
        String path = recipeDir + File.separator + fileName;
        return model.Recipe.fromXml(util.Util.readTextFile(path));
    }
    
    public model.Ingredient getIngredient(String fileName)
    {
        String ingredientDir = config.getValue( "ingredient dir", "ingredients" );
        String path = ingredientDir + File.separator + fileName;
        return model.Ingredient.fromXml(util.Util.readTextFile(path));
    }
    
    public boolean addIngredient( model.Ingredient ingredient )
    {
        String ingredientDir = config.getValue( "ingredient dir", "ingredients" );
        String path = ingredientDir + File.separator + ingredient.getTitle() + ".xml";
        
        if(util.Util.fileExists(path))
        {
            return false;
        }
        
        try
        {
            util.Util.writeTextFile(path, ingredient.toXmlString());
            return true;
        }
        catch (FileNotFoundException ex)
        {
            return false;
        }
        catch (IOException ex)
        {
            return false;
        }
    }
    
    public boolean addRecipe( model.Recipe recipe )
    {
        String recipeDir = config.getValue( "recipe dir", "recipes" );
        String path = recipeDir + File.separator + recipe.getTitle() + ".xml";
        
        if(util.Util.fileExists(path))
        {
            return false;
        }
        
        try
        {
            util.Util.writeTextFile(path, recipe.toXmlString());
            return true;
        }
        catch (FileNotFoundException ex)
        {
            return false;
        }
        catch (IOException ex)
        {
            return false;
        }
    }
}
